package bookStore.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bookStore.po.Role;
import bookStore.po.User;
import bookStore.service.privilege.RoleService;
import bookStore.service.privilege.RoleServiceImpl;
import bookStore.service.privilege.UserService;
import bookStore.service.privilege.UserServiceImpl;
import bookStore.tool.Constants;
import bookStore.tool.ParameterMapUtil;
import bookStore.tool.UploadTool;
import bookStore.tool.UrlUtil;
import cn.hutool.core.bean.BeanUtil;

/**
 * Servlet implementation class UserManagerController
 */
@WebServlet("/userManager/*")
@MultipartConfig
public class UserManagerController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String url;
	private String traget = "";
	Map<String, String> parametersMap;
	UserService userService = new UserServiceImpl();
	RoleService roleService = new RoleServiceImpl();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserManagerController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		url = UrlUtil.getUrl(request.getRequestURI());
		String offset="0";
		String pageSize=Constants.PAGE_SIZE+"";
		String userId="-1";
		switch(url) {
		case "list":
			offset=request.getParameter("pager.offset");
			pageSize = request.getParameter("pageSize");
			List<User> users = userService.queryAll(Integer.parseInt(offset), Integer.parseInt(pageSize));
			request.setAttribute("users", users);
			setTraget("/WEB-INF/manager/user/list.jsp");
			break;
			
		case "get":
			userId= request.getParameter("userId");
			User user = userService.get(Integer.parseInt(userId));
			
			//所有角色列表
			List<Role> allRoles = roleService.queryAll(0, Constants.PAGE_SIZE);
			//准备一个map，保存页面上角色checkbox的check属性
			Map<Integer,String> roleChecks = new HashMap<>();
			
			//当前用户所拥有的role
			List<Integer> roleIdsForUser = roleService.getRoleIdsByUser(Integer.parseInt(userId));
			
			//填写check属性值
			for(Role role:allRoles) {
				int roleId = role.getId();
				roleChecks.put(roleId, roleIdsForUser.contains(roleId)?"checked":"");
				
			}
			request.setAttribute("user", user);
			request.setAttribute("roleIds", roleIdsForUser);
			request.setAttribute("roleChecks", roleChecks);
			request.setAttribute("allRoles", allRoles);
			setTraget("/WEB-INF/manager/user/item.jsp");
			break;
		case "save":
			parametersMap = ParameterMapUtil.createParameterMapFormRequest(request);
			String pictureName = UploadTool.uploadFile(Constants.PICTURES_HOME, Constants.PICTURE_FILE_NAME, request);
			User newUser = BeanUtil.fillBeanWithMap(parametersMap, new User(), true);
			newUser.setPicture(Constants.PICTURES_PATH+pictureName);
			userService.register(newUser);
			break;
		case "toSaveForm":
			setTraget("/WEB-INF/manager/user/form.jsp");
			break;
		case "update":
			String [] roles = request.getParameterValues("roles");
			String username = request.getParameter("username");
			User updateUser =new User();
			updateUser.setId(Integer.parseInt(request.getParameter("id")));
			updateUser.setUsername(username);
			String fileName = request.getParameter("Constants.PICTURE_FILE_NAME");
			if(fileName!=null) {
				String updatePicture = UploadTool.uploadFile(Constants.PICTURES_HOME, Constants.PICTURE_FILE_NAME, request);
				updateUser.setPicture(Constants.PICTURES_PATH+updatePicture);
			}
			int [] roleIds=null;
			if(roles!=null&&roles.length>0) {
				roleIds = new int[roles.length];
				for(int i=0;i<roles.length;i++) {
					roleIds[i]=Integer.parseInt(roles[i]);
				}
			}
			userService.updateUserWithRole(updateUser, roleIds);
			
			break;
		case "delete":
			userId= request.getParameter("userId");
			userService.delete(Integer.parseInt(userId));
			setTraget("list?pager.offset=0&pateSize="+Constants.PAGE_SIZE);
			break;
	
		}
		if(traget.endsWith(".jsp")) {
			request.getRequestDispatcher(traget).forward(request, response);
		}else {
			response.sendRedirect(traget);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getTraget() {
		return traget;
	}

	public void setTraget(String traget) {
		this.traget = traget;
	}

	
}
